#!/bin/bash

if [ "$1" == "" ]; then
    echo 'Please specify the partition'
    exit
fi
usr_id=`id -u`
if [ "$usr_id" != "0" ]; then
    echo 'Please change to use root to execute this script'
    exit
fi

#####################################
##   initial enviorment            ##
#####################################
partition=${1}
org_src='/mnt/hgfs/linux-src/lfs/lfs-packages-6.7/sources'
LFS='/mnt/lfs'
SRC="${LFS}/sources"
BUILD="${LFS}/build"
TOOLS="${LFS}/tools"
USR='lfs'
export LFS SRC BUILD TOOLS USR
/sbin/mke2fs -jv ${partition}
mkdir -pv ${LFS}
mount -v -t ext3 ${partition} ${LFS}
mkdir -pv ${SRC} ${TOOLS} ${BUILD}
#mkdir -pv ${TOOLS}
ln -sv ${TOOLS} /
cp -r ${org_src}/* ${SRC}

/usr/sbin/groupadd ${USR}
/usr/sbin/useradd -s /bin/bash -g ${USR} -m -k /dev/null ${USR}
#passwd ${USR}
chown -v ${USR} ${TOOLS}
chown -v ${USR} ${SRC}
chown -v ${USR} ${BUILD}

function init_bash(){
	cat >/tmp/.bash_profile <<__EOF__
exec env -i HOME=\${HOME} TERM=\${TERM} PS1='\u:\w\$ ' /bin/bash
__EOF__

	cat >/tmp/.bashrc <<__EOF__
set +h
umask 022
LFS=${LFS}
LC_ALL=POSIX
LFS_TGT=$(uname -m)-lfs-linux-gnu
PATH=/tools/bin:/bin:/usr/bin
SRC="\${LFS}/sources"
BUILD="\${LFS}/build"
TOOLS="\${LFS}/tools"
export LFS LC_ALL LFS_TGT PATH SRC BUILD TOOLS
__EOF__

	lfs_home=`echo ~lfs`
	mv /tmp/.bash_profile ${lfs_home}/.bash_profile
	mv /tmp/.bashrc  ${lfs_home}/.bashrc
}

init_bash
su - ${USR}
#sudo -u ${USR} /bin/bash ${SRC}/compile.sh
#source ~/.bash_profile

#####################################
##  begin to compile               ##
#####################################


#####################################
##  after created clear enviorment ##
#####################################
umount ${LFS}
rm -r ${LFS}
rm /tools
/usr/sbin/userdel -rf ${USR}
#/usr/sbin/groupdel ${USR}

